/*
 * @desc:
 * @LastEditTime: 2024-03-20 18:42:45
 * @params:
 * @return::
 */
const { User } = require("../model");
const jwt = require("../util/jwt");
const { jwtSecret } = require("../config/config.default");
const dayjs = require("dayjs");
exports.getCurrentUser = async (req, res, next) => {
  console.log("getCurrentUser called");
  try {
    const user = await User.find({
      openId: req.body.user.openId,
    }); //添加一个映射 具体看 /model/article
    console.log(req.body, "---------user");
    // console.log(req.headers);
    res.status(200).json({
      user: user,
    });
  } catch (err) {
    console.log(err);
    next(err);
  }
};

exports.login = async (req, res, next) => {
  try {
    const user = req.thisUser.toJSON();
    console.log(user, "-----user");
    // const token = await jwt.sign(
    //   {
    //     userId: user._id,
    //     exp: Math.floor(Date.now() / 1000) + 60, // 1min 的过期事件
    //     //sign的第三个参数是一个对象 里面可以放一些东西
    //     //⬆就是过期时间
    //   },
    //   jwtSecret
    // );
    // const refreshToken = await jwt.sign(
    //   {
    //     userId: user._id,
    //     expiresIn: "1d", //1天的过期事件
    //   },
    //   jwtSecret
    // );
    delete user.password;
    res.status(200).json({
      ...user,
      token: "tempToken",
      refreshToken: "tempRefreshToken",
    });
  } catch (err) {
    console.log("用户登陆失败", err);
    next(err);
  }
};

exports.registers = async (req, res, next) => {
  try {
    // console.log(req.body);
    let user = new User(req.body.user);
    await user.save();
    // user = user.toJSON();
    // delete user.password;
    console.log(user, "-----user");

    res.status(201).json({
      status: 201,
      data: user,
      msg: "请求成功",
    });
    // res.send("/post");
  } catch (err) {
    console.log(err);
    next(err);
  }
};

exports.updateOid = async (req, res, next) => {
  try {
    const { openId, userId } = req.body;
    // console.log(req.body);
    // console.log(userId);
    if (userId) {
      const user = await User.findOne({
        _id: userId,
      });
      // user.openId = openId;
      // await user.save();
      // console.log(user);
    }
    // res.send("/updateOid");
    res.status(200).json({
      user: req.user,
    });
  } catch (err) {
    console.log(err);
    next(err);
  }
};
